package com.iplant.pdm.serviceImpl.dao.fmc;

import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.annotation.dao.DBBaseDAO;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.pdm.service.po.fmc.FMCLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

@DBBaseDAO(FMCLine.class)
public class FMCLineDAO extends BaseDAO {
    private static FMCLineDAO Instance = null;

    private static Logger logger = LoggerFactory.getLogger(FMCLineDAO.class);

    private FMCLineDAO() {
        super("");
        this.Init();
    }

    public static FMCLineDAO getInstance() {
        if (Instance == null)
            Instance = new FMCLineDAO();
        return Instance;
    }

    public void FMC_UpdateLine(BMSEmployee wLoginUser, FMCLine wLine, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);

        try {
            if (wLine == null || StringUtils.isEmpty(wLine.Name)) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }
            FMCLine wLineO = this.FMC_CheckLine(wLoginUser, wLine, wErrorCode);
            if (wLineO.ID > 0) {
                wErrorCode.set(ExceptionTypes.Duplication.getValue());
            }
            if (wErrorCode.Result != 0)
                return;

            Map<String, Object> wParams = new HashMap<String, Object>();

            wParams.put("FactoryID", wLine.FactoryID);
            wParams.put("ERPID", wLine.ERPID);
            wParams.put("PLMCode", wLine.PLMCode);
            wParams.put("Name", wLine.Name);
            wParams.put("Code", wLine.Code);
            wParams.put("Description", wLine.Description);
            wParams.put("ProductID", StringUtils.Join(",", wLine.ProductID));

            wParams.put("EditorID", wLoginUser.getID());
            wParams.put("EditTime", Calendar.getInstance());
            wParams.put("Active", wLine.Active);

            if (wLine.ID > 0) {
                wParams.put("ID", wLine.ID);
                super.Update(super.getTableName(), "ID", wParams);
            } else {
                wParams.put("CreatorID", wLoginUser.getID());
                wParams.put("CreateTime", Calendar.getInstance());
                wLine.ID = super.Insert(super.getTableName(), wParams);
            }

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("FMC_UpdateLine", ex);
        }
    }

    public void FMC_ActiveLine(BMSEmployee wLoginUser, FMCLine wLine, int wActive, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        // 判断客户信息是否存在(中国：统一社会信用代码，国外:提醒是否有重复）

        try {
            if (wLine == null || wLine.ID <= 0) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }

            Map<String, Object> wParams = new HashMap<String, Object>();

            wParams.put("ID", wLine.ID);
            wParams.put("EditorID", wLoginUser.getID());
            wParams.put("EditTime", Calendar.getInstance());
            wParams.put("Active", wActive);
            super.Update(super.getTableName(), "ID", wParams);

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());

            logger.error("FMC_ActiveLine", ex);
        }
    }

    public List<FMCLine> FMC_QueryLineList(BMSEmployee wLoginUser, int wFactoryID, String wName, int wActive,
                                           Pagination wPagination, OutResult<Integer> wErrorCode) {
        return this.FMC_QueryLineList(wLoginUser, -1, "", wFactoryID, null, wName, wActive, wPagination, wErrorCode);
    }

    private List<FMCLine> FMC_QueryLineList(BMSEmployee wLoginUser, int wID, String wCode, int wFactoryID,
                                            List<Integer> wProductID, String wName, int wActive, Pagination wPagination,
                                            OutResult<Integer> wErrorCode) {
        List<FMCLine> wFMCLineList = new ArrayList<FMCLine>();
        wErrorCode.set(0);

        try {
            if (wProductID == null)
                wProductID = new ArrayList<Integer>();
            wProductID.removeIf(p -> p <= 0);
            // Step02:查询
            Map<String, Object> wParams = new HashMap<String, Object>();
            String wSQLText = "";
            wSQLText = StringUtils.Format(
                    "Select t.*,t2.Name as FactoryName,t2.Code as FactoryCode, t3.Name as CreatorName ,"
                            + " t4.Name as EditorName,group_concat(distinct t5.Name) as ProductName,group_concat" +
                            "(distinct t5.Code) as ProductNo"
                            + " from {0}.fmc_line t   left join {0}.fmc_factory t2 on t.FactoryID=t2.ID "
                            + " left join {0}.mbs_user t3 on t.CreatorID=t3.ID "
                            + " left join {0}.mbs_user t4 on t.EditorID=t4.ID "
                            + " left join {0}.fpc_product t5 on find_in_set(t5.ID,t.ProductID) and t5.Active=1  "
                            + " where (:ID<=0 or  t.ID=:ID) and (:Code =''''  or  t.Code=:Code)"
                            + " AND (:FactoryID<=0 or  t.FactoryID=:FactoryID)"
                            + " AND (:Active<0 or  t.Active=:Active)   AND (:Name = '''' or  t.Name like :Name)"
                            + " AND (:ProductID = '''' or  t5.ID IN ({1}) )  group by t.ID ",
                    super.getDBName(), wProductID.size() > 0 ? StringUtils.Join(",", wProductID) : "0");

            wSQLText = this.DMLChange(wSQLText);

            wParams.put("ID", wID);
            wParams.put("FactoryID", wFactoryID);
            wParams.put("Code", wCode);
            wParams.put("Active", wActive);
            wParams.put("ProductID", StringUtils.Join(",", wProductID));
            wParams.put("Name", StringUtils.isEmpty(wName) ? "" : ("%" + wName + "%"));

            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams, wPagination);
            FMCLine wFMCLine = null;
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                wFMCLine = new FMCLine();
                wFMCLine.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                wFMCLine.Code = StringUtils.parseString(wSqlDataReader.get("Code"));
                wFMCLine.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                wFMCLine.FactoryID = StringUtils.parseInt(wSqlDataReader.get("FactoryID"));
                wFMCLine.FactoryCode = StringUtils.parseString(wSqlDataReader.get("FactoryCode"));
                wFMCLine.FactoryName = StringUtils.parseString(wSqlDataReader.get("FactoryName"));
                wFMCLine.ERPID = StringUtils.parseInt(wSqlDataReader.get("ERPID"));
                wFMCLine.PLMCode = StringUtils.parseString(wSqlDataReader.get("PLMCode"));
                wFMCLine.ProductID = StringUtils.splitStringList(wSqlDataReader.get("ProductID"), ",");
                wFMCLine.ProductName = StringUtils.parseString(wSqlDataReader.get("ProductName"));
                wFMCLine.ProductNo = StringUtils.parseString(wSqlDataReader.get("ProductNo"));
                wFMCLine.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));
                wFMCLine.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                wFMCLine.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                wFMCLine.CreatorName = StringUtils.parseString(wSqlDataReader.get("CreatorName"));
                wFMCLine.EditorName = StringUtils.parseString(wSqlDataReader.get("EditorName"));
                wFMCLine.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                wFMCLine.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
                wFMCLine.Description = StringUtils.parseString(wSqlDataReader.get("Description"));

                wFMCLineList.add(wFMCLine);
            }
            // Step03:配置系统
        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("FMC_QueryLineList", ex);
        }
        return wFMCLineList;
    }

    public FMCLine FMC_QueryLine(BMSEmployee wLoginUser, int wID, String wCode, OutResult<Integer> wErrorCode) {
        FMCLine wResult = new FMCLine();
        wErrorCode.set(0);

        try {
            List<FMCLine> wList = null;
            if (wID > 0) {
                wList = this.FMC_QueryLineList(wLoginUser, wID, "", -1, null, "", -1, Pagination.getDefault(),
                        wErrorCode);

            } else if (StringUtils.isNotEmpty(wCode)) {
                wList = this.FMC_QueryLineList(wLoginUser, -1, wCode, -1, null, "", -1, Pagination.getDefault(),
                        wErrorCode);
            }
            if (wList != null && wList.size() > 0) {
                wResult = wList.get(0);
            }
        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("FMC_QueryLineByID", ex);
        }
        return wResult;
    }

    public FMCLine FMC_CheckLine(BMSEmployee wLoginUser, FMCLine wFMCLine, OutResult<Integer> wErrorCode) {
        FMCLine wLine = new FMCLine();
        wErrorCode.set(0);

        try {

            // Step0:查询
            Map<String, Object> wParams = new HashMap<String, Object>();
            String wSQLText = StringUtils.Format("Select * from {0}.fmc_line "
                            + " where ID!=:ID and ((FactoryID=:FactoryID AND  Name =:Name) or (:Code != '''' and " +
                            "Code=:Code)) ",
                    super.getDBName());
            wParams.clear();
            wParams.put("ID", wFMCLine.ID);
            wParams.put("FactoryID", wFMCLine.FactoryID);
            wParams.put("Name", wFMCLine.Name);
            wParams.put("Code", wFMCLine.Code);

            wSQLText = this.DMLChange(wSQLText);
            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams);
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                wLine.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                wLine.FactoryID = StringUtils.parseInt(wSqlDataReader.get("FactoryID"));
                wLine.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                wLine.Code = StringUtils.parseString(wSqlDataReader.get("Code"));

                wLine.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                wLine.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                wLine.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                wLine.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
                wLine.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));

            }

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("FMC_CheckLine", ex);
        }
        return wLine;
    }

}
